package com.dstz.crm.core.manager.impl;

import java.util.Date;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dstz.base.api.exception.BusinessException;
import com.dstz.base.api.exception.BusinessMessage;
import com.dstz.base.manager.impl.BaseManager;
import com.dstz.crm.core.dao.GoodsDao;
import com.dstz.crm.core.dao.GoodsOrderDao;
import com.dstz.crm.core.manager.GoodsManager;
import com.dstz.crm.core.model.Goods;
import com.dstz.crm.core.model.GoodsOrder;
import com.dstz.org.api.model.IUser;
import com.dstz.org.api.service.UserService;
import com.dstz.sys.util.ContextUtil;
/**
 * 案例 Manager处理实现类
 * @author aschs
 * @email aschs@qq.com
 * @time 2018-08-24 18:06:04
 */
@Service("goodsManager")
public class GoodsManagerImpl extends BaseManager<String, Goods> implements GoodsManager{
	@Resource
	GoodsDao goodsDao;
	@Resource
	GoodsOrderDao goodsOrderDao;
	@Resource
	UserService userService;
	
	@Override
	@Transactional
	public void buyByIdAndNum(String id,long num) {
		if(num<1) throw new BusinessMessage("商品数量不可小于1");
		String currentUserId = ContextUtil.getCurrentUserId();
		Goods goods = goodsDao.get(id);
		if(goods==null) throw new BusinessException("商品不存在");
		Long credit2 = goods.getCredit();
		if(credit2==null||credit2<0) throw new BusinessException("商品积分不能为空或小于0");
		Long inventory = goods.getInventory();
		if(inventory!=null&&inventory>num) {
			IUser userById = userService.getUserById(currentUserId);
			if(userById==null)
				throw new BusinessException("用户不存在");
			Long credit = userById.getCredit();
			Long allCredit = credit2*num;
			if(credit!=null&&credit>allCredit) {
				userService.updateCredit(currentUserId, -allCredit,"购买商品,名称："+goods.getName()+",数量："+num);
			}else {
				throw new BusinessMessage("当前用户积分不足");
			}
			int updateInventory = goodsDao.updateInventory(id,-num);
			if(updateInventory!=1) throw new BusinessMessage("商品库存不足");
		}else {
			throw new BusinessMessage("商品库存不足");
		}
		GoodsOrder goodsOrder=new GoodsOrder();
		goodsOrder.setCreateBy(currentUserId);
		goodsOrder.setCreateTime(new Date());
		goodsOrder.setCredit(credit2);
		goodsOrder.setGoodsId(id);
		goodsOrder.setName(goods.getName());
		goodsOrder.setNum(num);
		goodsOrder.setPrice(goods.getPrice());
		goodsOrder.setAllCredit(num*credit2);
		goodsOrderDao.create(goodsOrder);
	}
}
